package com.gengzi.lot.item.service;

import com.gengzi.lot.common.pojo.PageResult;
import com.gengzi.lot.item.mapper.LotMapper;
import com.gengzi.lot.item.pojo.Lot;
import com.gengzi.lot.item.pojo.Menu;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class LotService {

    @Autowired
    private LotMapper lotMapper;

    public List<Lot> queryLotsByParkId(Long parkid) {
        Lot lot = new Lot();
        lot.setParkId(parkid);
        return this.lotMapper.select(lot);
    }

    public Lot queryLotByLotId(Long lotId,Long parkId) {
        Lot lot = new Lot();
        lot.setLotId(lotId);
        lot.setParkId(parkId);
        return this.lotMapper.selectOne(lot);
    }

    public Boolean addLot(Lot lot) {
        // 强制设置不能指定的参数为null
        lot.setId(null);
        // 查询 停车位是否存在
        Lot result = this.lotMapper.selectOne(lot);
        if (result != null){
            // TODO 打桩
            System.out.println("车位已存在！");
            return false;
        }
        // 添加到数据库
        boolean b = this.lotMapper.insertSelective(lot) == 1;
        //boolean b = this.userMapper.registerUser(user.getUsername(),user.getPassword()) == 1;
        return b;
    }

    public List<Lot> queryLots() {
        return this.lotMapper.selectAll();
    }

    @Transactional
    public void update(Lot lot) {
        // 查询以前lot
        Lot result = this.lotMapper.selectByPrimaryKey(lot.getId());
        if (result != null) {
            this.lotMapper.updateByPrimaryKeySelective(lot);
        }
    }

    public PageResult<Lot> queryLot(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
            // 开始分页
            PageHelper.startPage(page, rows);
            // 过滤
            Example example = new Example(Lot.class);
            if (StringUtils.isNotBlank(key)) {
                example.createCriteria().andLike("name", "%" + key + "%")
                        .orEqualTo("letter", key);
            }
            if (StringUtils.isNotBlank(sortBy)) {
                // 排序
                String orderByClause = sortBy + (desc ? " DESC" : " ASC");
                example.setOrderByClause(orderByClause);
            }
            // 查询
            Page<Lot> pageInfo = (Page<Lot>) this.lotMapper.selectByExample(example);
            // 返回结果
            return new PageResult<>(pageInfo.getTotal(), pageInfo);
    }
}
